package com.kamloo.stg.data.db;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class MySQLiteHelper extends SQLiteOpenHelper {

	private static final int DATABASE_VERSION = 1;
	private static final String DATABASE_NAME = "BusToGo.db";
	private static final String INITIAL_DB_DATA = "initialDB.sql";
	private static final String UPDATE_DB_DATA = "update_v";	
	private Context m_context;
	
	public MySQLiteHelper(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
		m_context = context;
	}
	
	@Override
	public void onCreate(SQLiteDatabase database) {
		// TODO : Complete code
	    //database.execSQL(AlarmDAO.TABLE_CREATE);
		database.execSQL(BookmarkDAO.TABLE_CREATE);
		Log.v("DATABASE", "OnCreate done");
		
		database.execSQL(DirectionDAO.TABLE_CREATE);
	    database.execSQL(LineDAO.TABLE_CREATE);
	    database.execSQL(NodeDAO.TABLE_CREATE);
	    database.execSQL(PeriodDAO.TABLE_CREATE);
	    database.execSQL(ScheduleDAO.TABLE_CREATE);
	    database.execSQL(StopDAO.TABLE_CREATE);
	    
	    initializeDbData(database);
	}
	
	@Override
	public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {
		try {
			InputStream input = m_context.getAssets().open(UPDATE_DB_DATA + DATABASE_VERSION + ".sql");
			executeSqlFile(new BufferedReader(new InputStreamReader(input)), database);	
		} catch (IOException e) { e.printStackTrace(); }
	}
	
	private void initializeDbData(SQLiteDatabase database)	{
		try {
			InputStream input = m_context.getAssets().open(INITIAL_DB_DATA);
			executeSqlFile(new BufferedReader(new InputStreamReader(input)), database);
			
		} catch (IOException e) { e.printStackTrace(); }
	}
	
	private void executeSqlFile(BufferedReader sqlFile, SQLiteDatabase database) throws IOException {
        String line;

        while ((line = sqlFile.readLine()) != null) {
            line = line.trim();
            database.execSQL(line);
        }

        sqlFile.close();
    }
	
} 